package farmaciaweb.com.br.dao.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import farmaciaweb.com.br.dao.ClienteDAO;
import farmaciaweb.com.br.entity.Cliente;
import farmaciaweb.com.br.entity.Telefone;
import farmaciaweb.com.br.util.JPAUtil;

@PersistenceContext(unitName = "FarmaciaWebJPA")
public class ClienteDAOImpl implements ClienteDAO{
	private static final long serialVersionUID = -6482561517277429223L;
	private EntityManager em;
	
	@Override
	public Cliente saveAtomic(Cliente cliente, List<Telefone> listaTelefones) {
		
		Cliente clienteSalvo;
		this.em = JPAUtil.getEntityManger();
		this.em.getTransaction().begin();
		clienteSalvo = this.em.merge(cliente);
		
		Iterator<Telefone> it = listaTelefones.iterator();
		while(it.hasNext()){
			Telefone telefone = it.next();
			telefone.setCliente(clienteSalvo);
			this.em.persist(telefone);
		}
		
		
		this.em.getTransaction().commit();
		this.em.close();
		
		return clienteSalvo;
	}
	
	@Override
	public void deleteAtomic(Cliente cli) {
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			this.em.remove(cli);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			e.getStackTrace();
		}	
		
	}
	
	public List<Cliente> pesquisarCliente(String nome, String cpf){
		Map<String, Object> listaParams;
		listaParams = new HashMap<String, Object>();
		listaParams.put("nome", nome);
		listaParams.put("cpf", cpf);
		return JPAUtil.findByNamedQueryAndNamedParams("bd_farmaciaweb.consultaCliente", listaParams);
	}
	
	public Cliente findById(int id){
		Cliente t = new Cliente();
		t = em.find(Cliente.class, id);
		return t;
	}

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}